import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_stort/config/routes.dart';
import 'package:flutter_stort/utils/jump_util.dart';
import '../utils/shared_preferences_utils.dart';

class WelcomePage extends StatefulWidget {
  @override
  _WelcomePageState createState() => _WelcomePageState();
}

class _WelcomePageState extends State<WelcomePage> {
  int _seconds = 3;
  Timer _countdownTimer;
  int userId = -1;
  @override
  void initState() {
    SharedPreferencesUtils.getInt("userId").then((int id) {
      userId = id ?? 0;
    });
    _startCountdown();
    super.initState();
  }

  ///初始化开始计时器
  void _startCountdown() {
    if (_countdownTimer != null) {
      return;
    }
    _countdownTimer = new Timer.periodic(Duration(seconds: 1), (timer) {
      setState(() {
        if (_seconds > 1) {
          _seconds--;
        } else {
          _startNextPage();
        }
      });
    });
  }

  ///关闭定时器
  void _closeCountdown() {
    if (_countdownTimer != null) {
      _countdownTimer.cancel();
      _countdownTimer = null;
    }
  }

  ///跳转到下一个界面
  void _startNextPage() {
    _closeCountdown();
    JumpPageUtils.clostPage(context);
    if (userId > 0) {
      JumpPageUtils.startNext(context, RoutesUtils.MAIN_ROOT);
    } else {
      JumpPageUtils.startNext(context, RoutesUtils.LOGIN_ROOT);
    }
  }

  @override
  void dispose() {
    _closeCountdown();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        height: double.infinity,
        padding: EdgeInsets.fromLTRB(0, 50, 30, 0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              height: 34,
              child: RaisedButton(
                onPressed: _startNextPage,
                child: Text(
                  "跳过  $_seconds",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 12,
                  ),
                ),
                color: Colors.black.withOpacity(0.4),
                shape: StadiumBorder(),
              ),
            ),
          ],
        ),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/welcome.jpg"),
            fit: BoxFit.fill,
          ),
        ),
      ),
    );
  }
}
